<?php


namespace App\Logic;


use App\Base\AuthManager;
use App\Base\ErrCode;
use App\Base\Response;
use App\Support\Database\DbManager;
use App\Support\Time\Time;
use App\Utility\Jwt;

class UserLogic
{
    public function encrpt($word)
    {
        return md5($word);
    }

    /**
     * 注册
     * @param $param
     * @return array
     */
    public function register($param)
    {
        arrayAddslashes($param);
        $db = DbManager::getInstance();
        $exists = $db->first("SELECT 1 FROM user where username = '{$param['username']}'");

        if ($exists) {
            return [ErrCode::$failCode, [], '用户名重复'];
        }
        //数据库username唯一索引，避免重复
//        password_hash();
//        password_verify();
        try {
            $db->insert(
                'user',
                [
                    'username' => $param['username'],
                    'password' => $this->encrpt($param['password']),
                    'created_at' => Time::now()->toDateTime()
                ]
            );
        } catch (\Throwable $throwable) {
            return [ErrCode::$failCode, [], '请稍后再试'];
        }

        return [ErrCode::$successCode, [], '注册成功'];
    }


    public function login($param)
    {
        arrayAddslashes($param);
        $db = DbManager::getInstance();
        $password = $this->encrpt($param['password']);

        $user = $db->first(
            "SELECT userid, username FROM user where username = '{$param['username']}' AND password = '{$password}' limit 1"
        );

        if (!$user) {
            return [ErrCode::$failCode, [], '用户名或密码错误'];
        }

        $token = Jwt::init()->getToken($user);
        return [ErrCode::$successCode, ['token' => $token], '登录成功'];
    }

    public function refreshToken()
    {
        $user = AuthManager::getPayload();
        $token = Jwt::init()->getToken($user);
        return [ErrCode::$successCode, ['token' => $token], 'token刷新成功'];
    }
}